package twi.query;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import twi.OWLModel;
import twi.Storable;
import twi.filter.Filter;
import twi.filter.NodeFilter;
import twi.filter.impl.AnonFilter;
import twi.filter.impl.ClassNodeFilter;
import twi.filter.impl.DomainRangeFilter;
import twi.filter.impl.TypeNodeFilter;

public abstract class Query implements Storable {

	protected OWLModel model;
	protected ArrayList<Filter> filter = new ArrayList<Filter>();
	private ArrayList<Filter> nodeFilter = new ArrayList<Filter>();
	protected int transitivity = 0;
	protected boolean transitivityBevorFilter = true;

	public Query(OWLModel model) {
		this();
		this.model = model;
	}

	protected Query() {
		filter.add(new AnonFilter());
		nodeFilter.add(new TypeNodeFilter(true));
		nodeFilter.add(new ClassNodeFilter());
		nodeFilter.add(new DomainRangeFilter(true));
//		nodeFilter.add(new Filter(){
//
//			@Override
//			public boolean isValid(RDFNode node) {
//				String n =Utils.getLocalName(node); 
//				if (n.equals("ObjectProperty"))
//					return false;
//				if (n.equals("FunctionalProperty"))
//					return false;
//				return true;
//			}
//
//			@Override
//			public void decodeString(String filterString) {
//				// TODO Auto-generated method stub
//				
//			}
//
//			@Override
//			public String encodeString() {
//				// TODO Auto-generated method stub
//				return null;
//			}
//			
//		});
	}

	public abstract String getSPARQLString();

	public static String createPrefixDeclarations(OWLModel model) {
		String queryString = "";
		queryString += "BASE <"
				+ model.getBasePrefix().substring(0,
						model.getBasePrefix().length() - 1) + ">\n";
		queryString += "PREFIX : <" + model.getBasePrefix() + ">\n";
		Map prefmap = model.getNsPrefixMap();
		Iterator iter = prefmap.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			if (key.length() == 0 || key.equals(" "))
				continue;
			String val = (String) prefmap.get(key);
			queryString += "PREFIX " + key + ": <" + val + ">\n";
		}
		return queryString;
	}

	public OWLModel getModel() {
		return model;
	}

	public ArrayList<Filter> getFilter() {
		return filter;
	}

	public void addFilter(Filter f) {
		if (f != null)
			this.filter.add(f);
	}

	public int getTransitivity() {
		return transitivity;
	}

	public void setTransitivity(int transitivity) {
		this.transitivity = transitivity;
	}

	public boolean isTransitivityBevorFilter() {
		return transitivityBevorFilter;
	}

	public void setTransitivityBevorFilter(boolean transitivityBevorFilter) {
		this.transitivityBevorFilter = transitivityBevorFilter;
	}

	public ArrayList<Filter> getNodeFilter() {
		return this.nodeFilter;
	}

	public void addNodeFilter(NodeFilter nf) {
		if (nf != null)
			nodeFilter.add(nf);
	}
}
